import {InjectionToken} from "@angular/core";

export interface Scripts {
    name: string;
    src: string;
}

export const SCRIPT_LOADER = new InjectionToken('script_loader');




export class ScriptLoader {
    public _scripts: any = {};

    constructor(private scriptStore: Scripts[]) {
        scriptStore.forEach((script) => {
            this._scripts[script.name] = {
                src: script.src,
                loaded: false,
            };
        });
    }

    public getScript(name: string): Object {
        return this._scripts[name];
    }

    public getAllScript(): Object {
        return this._scripts;
    }

    public load(...scripts: string[]) {
        const promises: any[] = [];
        scripts.forEach((script) => {
            promises.push(this.loadScripts(script));
        })
        return Promise.all(promises);
    }

    public loadScripts(name: string) {
        return new Promise((resolve, reject) => {
            if (this._scripts[name].loaded) {
                resolve({script: name, loaded: true, status: `Already loaded script：${name}`});
            } else {
                const script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = this._scripts[name].src;

                script.onload = () => {
                    this._scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: `loaded`});
                };
                script.onerror = () => resolve({script: name, loaded: false, status: 'loaded'});
                document.getElementsByTagName('head')[0].appendChild(script);
            }
        });
    }
}
